from datetime import timedelta
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from database import get_db
from models import User
from schemas import UserCreate, UserSchema, Token, ResponseModel
from utils import create_access_token, log_operation
from api.deps import get_current_active_user, get_client_ip
import hashlib
import base64

# 简单的密码验证函数
def simple_verify_password(plain_password, hashed_password):
    # 使用MD5哈希来验证密码，与init_users.py中的哈希方法保持一致
    expected_hash = hashlib.md5(plain_password.encode()).hexdigest()
    return hashed_password == expected_hash
from api.deps import get_current_active_user

router = APIRouter()

@router.post("/login", response_model=ResponseModel[Token])
def login_for_access_token(
    request: Request,
    db: Session = Depends(get_db),
    form_data: OAuth2PasswordRequestForm = Depends()
) -> Any:
    """用户登录获取访问令牌"""
    ip_address = get_client_ip(request)
    
    try:
        user = db.query(User).filter(User.username == form_data.username).first()
        
        if not user or not simple_verify_password(form_data.password, user.password):
            # 记录登录失败日志
            log_operation(
                db=db,
                user_id=None,
                username=form_data.username,
                ip_address=ip_address,
                operation_type="login",
                operation_content=f"用户 {form_data.username} 登录失败：用户名或密码错误",
                success=0
            )
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误",
                headers={"WWW-Authenticate": "Bearer"},
            )
        
        if user.status != "1":
            # 记录登录失败日志
            log_operation(
                db=db,
                user_id=user.id,
                username=user.username,
                ip_address=ip_address,
                operation_type="login",
                operation_content=f"用户 {user.username} 登录失败：用户未激活",
                success=0
            )
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="用户未激活"
            )
    
        # 创建访问令牌
        access_token_expires = timedelta(hours=24)
        access_token = create_access_token(
            data={"sub": user.username},
            expires_delta=access_token_expires
        )
        
        # 记录登录成功日志
        log_operation(
            db=db,
            user_id=user.id,
            username=user.username,
            ip_address=ip_address,
            operation_type="login",
            operation_content=f"用户 {user.username} 登录成功",
            success=1
        )
        
        return ResponseModel(data=Token(access_token=access_token, token_type="bearer"))
    except HTTPException:
        raise
    except Exception as e:
        # 记录其他登录错误
        log_operation(
            db=db,
            user_id=None,
            username=form_data.username,
            ip_address=ip_address,
            operation_type="login",
            operation_content=f"用户 {form_data.username} 登录异常：{str(e)}",
            success=0
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="登录过程中发生错误"
        )

@router.get("/me", response_model=ResponseModel[UserSchema])
def get_current_user_info(
    current_user: User = Depends(get_current_active_user)
) -> Any:
    """获取当前用户信息"""
    return ResponseModel(data=current_user)

@router.post("/register", response_model=ResponseModel[UserSchema])
def register_user(
    user_in: UserCreate,
    db: Session = Depends(get_db)
) -> Any:
    """用户注册"""
    # 检查用户名是否已存在
    user = db.query(User).filter(User.username == user_in.username).first()
    if user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已存在"
        )
    
    # 检查邮箱是否已存在
    if user_in.email:
        user = db.query(User).filter(User.email == user_in.email).first()
        if user:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="邮箱已被注册"
            )
    
    # 创建新用户
    from utils import get_password_hash
    hashed_password = get_password_hash(user_in.password)
    db_user = User(
        username=user_in.username,
        password=hashed_password,
        email=user_in.email,
        phone=user_in.phone,
        department_id=user_in.department_id,
        status="1" if user_in.is_active else "0"
    )
    
    # 添加角色
    if user_in.role_ids:
        from models import Role
        roles = db.query(Role).filter(Role.id.in_(user_in.role_ids)).all()
        db_user.roles = roles
    
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    
    return ResponseModel(data=db_user)